package com.ttbj.controller.yitong;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ttbj.api.yitong.CutPayService;
import com.ttbj.api.yitong.WithdrawService;
import com.ttbj.api.yitong.YTFinancialService;
import com.ttbj.api.yitong.YtPayService;


@Controller
public class YTFinancialController {/*
	
	@Autowired
	private YTFinancialService ytFinancialService;
	@Autowired
	private ScanQRCodeService scanQRCodeService;
	@Autowired
	private CutPayService cutPayService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private YtPayService ytPayService;
	
	private static final Logger logger = LoggerFactory.getLogger(YTFinancialController.class);
	
	
	//测试提现
	@RequestMapping(value="/ytFinancial/cs_withdraw.htm")
	public void cs_withdraw(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("cs_withdraw..............");
//		WithdrawData wData = new WithdrawData();
//		wData.setOrderNo(orderNo);
//		wData.setAccountNo("0166922028682182656");
//		wData.setAmount("1.00");
//		wData.setBackNotifyUrl("http://2195n908w3.51mypc.cn:80/zywl-backstage-web/ytFinancial/wd_notify.htm");
//		Map<String, String> map = this.ytFinancialService.getYTFinancialResult(wData, 10, "withdraw");
//		logger.info("返回的状态值是 {}", map.get("status"));
//		return "forward:/ytFinancial/cs_wd_notify.htm";	//这个地方是是测试，直接调用下面那个提现通知controller
		
		this.withdrawService.withrawOperation("123456", "0165863433643360256", "0.1", "OS001220180045", "admin");
		response.getWriter().print("cs_withdraw..............");
	}
	
	
	//测试提现通知
	@RequestMapping(value="/ytFinancial/wd_notify.htm")
	public void wd_notify(HttpServletRequest request, HttpServletResponse response) {
		try {
			//从body中获取报文生成字符串
			String noticeStr = readAsChars(request);
			System.out.println("回调通知报文：" + noticeStr);
			Map<String, String> notifyMap = this.ytFinancialService.getWdNotify(noticeStr);
			for(Map.Entry<String, String> entry : notifyMap.entrySet()) {
				System.out.println(entry.getKey() + "----" + entry.getValue());
			}
			response.getWriter().print("success");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	----------------------------------------------分隔符--------------------------------------------------------------
	
	
	//扫码下单，并把二维码地址返回到页面生成二维码
	@RequestMapping(value="/qrPayment.htm")
	public String qrPayment(HttpServletRequest request, Model model) throws Exception{
		String merOrderNum = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10) + "_CS";
		String tranAmt = "10";
		String sysTraceNum = String.valueOf(new Random().nextInt(2147483647) + 1);
		String activeTime = "";	//设置扫码支付有效期，不传的话默认3分钟
		String attach = "";	//附加数据，查询时返回原样
		String payPage = "true";	//是否显示易通支付页面，默认true，不显示为false
		String backURL = "http://2195n908w3.51mypc.cn/zywl-backstage-web/qrBackUrl.htm";	//主扫异步回调
		ActiveScanQRCodeData data = new ActiveScanQRCodeData(merOrderNum, tranAmt, sysTraceNum, payPage);
		data.setBackURL(backURL);
		data.setAttach("xxxxxxxxxxxx");
		
		Map<String, String> map =  this.scanQRCodeService.activeScanQrCode(data);
		String respCode = map.get("respCode");
		if ("0000".equals(respCode)) {
			model.addAttribute("codeurl", map.get("codeUrl"));
		}else {
			model.addAttribute("respMsg", map.get("respMsg"));
		}
		return "qrcode";
	}
	
	
	//商户返回页面，展示支付成功
	@RequestMapping(value="/qrCodeMerUrl.htm")
	public String qrCodeMerUrl(HttpServletRequest request, HandlePayData handlePayData){
		logger.info("---->>>>merURL中qrCodeMerUrl() 方法已经被回调");
		System.out.println("merURL的：" + handlePayData.toString());
		return "paySuccess";
	}
	
	
	//主扫支付成功后的异步回调方法：必须返回字符串 "success"
	@RequestMapping(value="/qrBackUrl.htm")
	public void qrBackUrl(HttpServletRequest request, HttpServletResponse response, HandlePayDataDto handlePayData) throws Exception{
		logger.info("---->>>>backURL中qrBackUrl() 方法已经被回调");
		logger.info("支付成功后报文转换成bean后：{}", handlePayData.toString());
		Map<String, Object> map = null;
		try {
			//对支付请求应答报文进行验签，验签不通过，则直接抛出异常，通过则取出响应的信息
			map = this.scanQRCodeService.activeCallBackFunction(handlePayData);
			for (Map.Entry<String, Object> entry: map.entrySet()) {
				System.out.println(entry.getKey() + "-->" + entry.getValue());
			}
			response.getWriter().print("success");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().print("failed");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		//保存支付信息
		int i = this.ytPayService.addToPaymentRecord(handlePayData);
		logger.info("保存支付信息几条：{}", i);
//		if (null != map) {
//			String paymentOrderNo = (String) map.get("orderId");	//支付订单号(主扫中的支付网关订单号)
//			String orderNum = "WEB038618092220205";		//merOrderNum
//			String amount = (String) map.get("tranAmt");
//			//因为异步回调总是调用好几次，造成重复分账，需要使用paymentOrderNo查询数据库，如果有，则不执行分账了，如果没有，则才进行分账(待定)
//			Map<String, String> cutPayMap = this.cutPayService.orderCutPay(paymentOrderNo, orderNum, amount);
//			for (Map.Entry<String, String> entry: cutPayMap.entrySet()) {
//				System.out.println(entry.getKey() + "->>" + entry.getValue());
//			}
//		}
//		try {
//			response.sendRedirect(request.getContextPath() + "/jumpToPage.htm?respCode=" + map.get("respCode"));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return "success";
//		request.getRequestDispatcher("/jumpToPage.htm?respCode=" + map.get("respCode")).forward(request, response);
//		String respCode = (String) map.get("respCode");
//		return "forward:/jumpToPage.action?respCode=" + respCode;
	}
	
	
	//被调用的controller，用于返回成功或失败页面
	@RequestMapping(value="/jumpToPage.htm")
	public String jumpToPage(HttpServletRequest request, String respCode) {
		System.out.println("jumpToPage..respCode:" + respCode);
		String jumpUrl = "";
		if ("0000".equals(respCode)) {
			jumpUrl = "paySuccess";
		}else {
			jumpUrl = "payFail";
		}
		return jumpUrl;
	}
	
	
	//支付查询
	@RequestMapping(value="/payQuery.htm")
	public void wxsp_Payquery(HttpServletResponse response, 
							@RequestParam String merOrderNum, @RequestParam String tranDate) throws Exception {
		logger.info("wxsp_Payquery()方法执行.....");
		Map<String, String> mapData = this.scanQRCodeService.transactionQuery(merOrderNum, tranDate, 2);
		for (Map.Entry<String, String> entry : mapData.entrySet()) {
			System.out.println(entry.getKey() + "->" + entry.getValue());
		}
		response.getWriter().println(mapData.get("respCode"));
	}
	
	
	//微信小程序调起微信支付(下单并进行支付)
	@RequestMapping(value="/wxsp_payment.htm", method=RequestMethod.POST)
	@ResponseBody
	public String wxsp_payment(HttpServletRequest request, HttpServletResponse response) throws Exception{
		PassiveScanQRCodeData data = new PassiveScanQRCodeData();
		String merOrderNum = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10) + "_CS";
		String sysTraceNum = String.valueOf(new Random().nextInt(2147483647) + 1);
		String tranAmt = "10";
		data.setMerOrderNum(merOrderNum);
		data.setSysTraceNum(sysTraceNum);
		data.setTranAmt(tranAmt);
		data.setChannel(PassiveORCodeEnum.WX_SP.getDesc());
		data.setSub_openid("ooYlo5Fca2gq5qgAxGVBtQFhEjWc");
		data.setBackURL("http://2195n908w3.51mypc.cn/zywl-backstage-web/wxsp_qrBackUrl.htm"); //微信小程序异步回调
		data.setAttach("AAAAAAAAA");	//附加数据
		Map<String, String> map = this.scanQRCodeService.passiveScanQrCode(data);
		for(Map.Entry<String, String> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "->" + entry.getValue());
		}
		JsonObject jsonObject = null;
		if (map.get("respCode").equals("0000")) {
			jsonObject = new JsonParser().parse(map.get("payInfo")).getAsJsonObject();
		}else {
			jsonObject = new JsonObject();
		}
		jsonObject.addProperty("respCode", map.get("respCode"));
		jsonObject.addProperty("respMsg", map.get("respMsg"));
		return jsonObject.toString();
	}
	
	
	//微信小程序支付完成后的异步回调方法：必须返回字符串 "success"
	@RequestMapping(value="/wxsp_qrBackUrl.htm")
	public void wxsp_qrBackUrl(HttpServletRequest request, HttpServletResponse response, PassiveScanQRCodeData data) throws Exception{
		logger.info("---->>>>backURL中wxsp_qrBackUrl() 方法已经被回调");
		Map<String, Object> map = null;
		try {
			map = this.scanQRCodeService.passiveCallBackFunction(data);
			for (Map.Entry<String, Object> entry: map.entrySet()) {
				System.out.println(entry.getKey() + "->" + entry.getValue());
			}
			response.getWriter().print("success");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().print("failed");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		//保存支付信息
		int i = this.ytPayService.addToPaymentRecord(data);
		if (null != map) {
			String paymentOrderNo = (String) map.get("orderId");	//支付订单号(被扫中的支付网关订单号)
			String orderNum = "WEB038618092220205";		//merOrderNum
			String amount = (String) map.get("tranAmt");
			//因为异步回调总是调用好几次，造成重复分账，需要使用paymentOrderNo查询数据库，如果有，则不执行分账了，如果没有，则才进行分账(待定)
			Map<String, String> cutPayMap = this.cutPayService.orderCutPay(paymentOrderNo, orderNum, amount);
			for (Map.Entry<String, String> entry: cutPayMap.entrySet()) {
				System.out.println(entry.getKey() + "->>" + entry.getValue());
			}
		}
	}
	
	
	*//**
	 * 从 HttpServletRequest 中读取HTTP请求的body内容
	 * @param request HttpServletRequest对象
	 * @return body里的内容
	 *//*
	private String readAsChars(HttpServletRequest request) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str;
			while((str = br.readLine()) != null) {
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
*/}
